var template = `
<div class="crack">
    <div v-if="crackMsg.length > 0" class="msg">
        <div>-- 破解模块 --</div>
        <div v-for="key,index in crackMsg">[{{index+1}}] {{key}}</div>
        <div>破解耗时{{pastTime}}ms</div>
    </div>
    <div :class="'crack-'+!!queryHash" v-else>[破解结果] {{queryHash?'解密成功':'解密失败'}}</div>
    <hr/>
</div>
`;

let Crack = {
    name: 'Crack',
    components: {},
    template,
    data() {
        const {useSlots} = Vue;
        return {
            sharedState: store.state,
            controlSlot: !!useSlots().default,
            crackMsg: [],
            queryHash: '',
            parser: new DOMParser(),
            startTime: new Date().getTime(),
            pastTime: 0,
        }
    },
    methods: {
        async doCrack() {
            /*
            // https://www.instagram.com/
            dom=0;fetch('/').then(res=>res.text().then(t=>{p=new DOMParser();dom=p.parseFromString(t,'text/html')}))
            s=dom.documentElement.getElementsByTagName('script');
            src=Array.from(s).filter(el=>el.src).map(el=>el.src).filter(sr=>sr.indexOf('ConsumerLibCommons')>0)[0]
            js=0;fetch(src).then(res=>res.text().then(t=>js=t))
            queryHash=js.split('\n').filter(t=>t.indexOf('queryId')>0).join(';').split(';').filter(t=>t.indexOf('queryId')>0&&t.indexOf('timeout')>0)[0].split('queryId')[1].split('timeout')[0].split('"')[1].split('"')[0]
             */
            this.logMsg('开始破解[queryHash]')
            let src = '';
            await this.getForHomeHtml().then(html => {
                if (html) {
                    this.logMsg('已获取首页数据11')
                } else {
                    this.logMsg('获取首页数据失败')
                }
                let dom = this.parser.parseFromString(html, 'text/html')
                let scriptElements = dom.documentElement.getElementsByTagName('script');
                src = Array.from(scriptElements).filter(el => el.src).map(el => el.src).filter(sr => sr.indexOf('ConsumerLibCommons') > 0)[0];
                if (src) {
                    this.logMsg('已获取密码地址')
                } else {
                    this.logMsg('获取密码地址失败')
                }
            }).catch(err => {
                this.logMsg('破解异常 err=' + String(err))
                console.log(err)
            })
            if (src) {
                await this.getForText(src).then(text => {
                    if (text) {
                        this.logMsg('已获取密码数据')
                    } else {
                        this.logMsg('获取密码数据失败')
                    }
                    this.logMsg('已获取密码数据')
                    let lines = text.split('\n').filter(t => t.indexOf('queryId') > 0).join(';').split(';').filter(t => t.indexOf('queryId') > 0 && t.indexOf('timeout') > 0)[0].split('queryId')[1].split('timeout').filter(t => t.indexOf('queryParams') > 0).join('').split('"')
                    if (lines.length === 3) {
                        this.queryHash = lines[1]
                        this.sharedState.queryHash = this.queryHash
                        this.logMsg('已解密密码数据')
                        this.logMsg('-- 破解成功 --')
                    } else {
                        this.logMsg('解密密码数据失败')
                    }
                }).catch(err => {
                    this.logMsg('获取密码数据失败 err=' + String(err))
                })
            }
            setTimeout(() => this.crackMsg = [], 10000)
        },
        logMsg(msg) {
            let newMsg = []
            if (Array.isArray(msg)) {
                msg.forEach(e => newMsg.push([new Date().fmt('[yyyy-MM-dd HH:mm:ss]'), e].join(' ')))
            } else {
                newMsg.push([new Date().fmt('[yyyy-MM-dd HH:mm:ss]'), msg].join(' '))
            }
            this.crackMsg.push(...newMsg)
            console.log(...newMsg)
            this.pastTime = new Date().getTime() - this.startTime
        },
        getForText(src) {
            return new Promise((resolve, reject) => {
                if (!src) {
                    let msg = ['src 地址不能为空 ', src]
                    this.$message({message: msg, level: 'error'})
                    console.log(...msg)
                    reject(msg)
                    return
                }
                axios.get(src).then(res => {
                    if (res.data && res.status === 200) {
                        let html = res.data
                        resolve(html)
                    } else {
                        let msg = ['获取TEXT失败', src]
                        this.$message({message: msg, level: 'error'})
                        console.log(...msg, res)
                        resolve('')
                    }
                }).catch(err => {
                    let msg = ['获取TEXT失败 err', src]
                    this.$message({message: msg, level: 'error'})
                    console.log(...msg, err)
                    resolve('')
                })
            })
        },
        getForHomeHtml() {
            return new Promise((resolve, reject) => {
                axios.get('/').then(res => {
                    if (res.data && res.status === 200) {
                        let html = res.data
                        resolve(html)
                    } else {
                        let msg = ['获取首页HTML失败']
                        this.$message({message: msg, level: 'error'})
                        console.log(...msg, res)
                        resolve('')
                    }
                }).catch(err => {
                    let msg = ['获取首页HTML失败 err']
                    this.$message({message: msg, level: 'error'})
                    console.log(...msg, err)
                    resolve('')
                })
            })
        }
    },
    mounted: () => {
        const {proxy} = Vue.getCurrentInstance();
        console.log('%s mounted', proxy.$options.name);
        proxy.doCrack();
    },
};